<?php
namespace App\Service\AppService;
class ArrayToXML  
{  
    public static function arrForeach($arr) {  
        if (!is_array ($arr)) {  
            return false;  
        }  
        $xml='';  
        foreach($arr as $key => $value){  
            $xml .= is_numeric($key)?"":"<{$key}>";  
            $xml .= is_array($value)? self::arrForeach($value):$value;  
            $xml .= is_numeric($key)?"":"</{$key}>\n";  
        }  
        return $xml;  
    }  
    public static function toXml($post){  
        foreach ($post as $key => $value) {      
            $attribute = '';    
            $str = '';   
            $strFot='';
            foreach ($value as $k1 => $v1) {  
  
                if(is_array($v1)){  //如果含有数组  
                    $str .= is_numeric($k1)?"":"<{$k1}>";  
                    $str .= self::arrForeach($v1);  
                    $str .= is_numeric($k1)?"":"</{$k1}>";  
                }else{  
                    $attribute .= $k1.'="'.$v1.'" ';  
                }  
            }  
            $strHead = '<?xml version="1.0" encoding="UTF-8"?>';  
            $strHead .= '<'.$key.' '.$attribute.'>'; //key为第一行标签名称 + 第一行的属性  
            $strFot .= '</'.$key.'>';  
        }  
        $string = $strHead.$str.$strFot;  
        return $string;  
    }  
  
    public static function to_xml2(SimpleXMLElement $object, array $data, $level)  
    {     
        foreach ($data as $key => $value) {  
            if (is_array($value)) {  
                if (is_numeric($key)) { //是数字用上级$object做父元素  
                    $tnum = $level + 1;  
                    self::to_xml2($object, $value, $tnum);  
                } else {  //不是数字直接创建元素$new_object做父元素  
                    $new_object = $object->addChild($key);  
                    $newLevel = $level + 1;  
                    self::to_xml2($new_object, $value, $newLevel);  
                }  
            } else {  
                if ($level == 1) { //第一层级  
                    $object->addAttribute($key, $value);  
                } else {  
                    $object->addChild($key, $value);  
                }  
            }  
  
        }    
  
    }   
  
    /** 
     * 保存文件 
     *  
     * @param string $fileName 文件名（含相对路径） 
     * @param string $text 文件内容 
     * @return boolean  
     */  
    public static function saveFile($fileName, $text) {  
        if (!$fileName || !$text)  
            return '失败1';  
        if(!file_exists(dirname($fileName)))  
        {  
            mkdir(dirname($fileName));  
        }  
        if ($fp = fopen($fileName, "w")) {  
                if (@fwrite($fp, $text)) {  
                    fclose($fp);  
                    return '成功';  
                } else {  
                    fclose($fp);  
                    return '失败2';  
                }   
            }   
  
        return '失败';  
    }   
  
  
  
}  